/**
 * API请求工具类
 * 处理与后端服务器的通信
 */
// const BASE_URL = 'http://localhost:5002/api'; // 开发环境
const BASE_URL = 'https://jingludian.seeking2020.cn/api'; // 生产环境

class ApiClient {
  constructor() {
    this.token = wx.getStorageSync('token') || null;
  }

  /**
   * 设置认证令牌
   */
  setToken(token) {
    this.token = token;
    wx.setStorageSync('token', token);
  }

  /**
   * 清除认证令牌
   */
  clearToken() {
    this.token = null;
    wx.removeStorageSync('token');
  }

  /**
   * 发送请求
   */
  async request(url, options = {}) {
    // 添加重试标记，防止死循环
    const isRetry = options._retry || false;
    
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    };

    // 如果有token，添加到请求头
    if (this.token) {
      header['Authorization'] = `Bearer ${this.token}`;
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: BASE_URL + url,
        method: options.method || 'GET',
        data: options.data || {},
        header,
        success: async (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else if (res.statusCode === 401) {
            // 如果已经是重试请求还失败，则不再重试，直接返回错误
            if (isRetry) {
              this.clearToken();
              reject(new Error('登录已过期，请重新登录'));
              return;
            }
            
            // token过期，尝试自动重新登录
            try {
              // 清除过期的token
              this.clearToken();
              
              // 获取微信登录凭证
              const loginRes = await new Promise((resolve, reject) => {
                wx.login({
                  success: resolve,
                  fail: reject
                });
              });
              
              if (loginRes.code) {
                // 获取用户信息
                const userInfo = await new Promise((resolve) => {
                  wx.getUserProfile({
                    desc: '用于完善用户资料',
                    success: (res) => {
                      resolve({
                        nickName: res.userInfo.nickName,
                        avatarUrl: res.userInfo.avatarUrl,
                        gender: res.userInfo.gender,
                        province: res.userInfo.province,
                        city: res.userInfo.city,
                        country: res.userInfo.country
                      });
                    },
                    fail: () => {
                      // 如果用户拒绝授权，使用默认信息
                      resolve({
                        nickName: '匿名用户',
                        avatarUrl: ''
                      });
                    }
                  });
                });
                
                // 调用后端登录接口
                const loginData = await this.wechatLogin(loginRes.code, userInfo);
                
                // 保存新的token
                this.setToken(loginData.access_token);
                
                // 重新发送原请求，标记为重试请求
                const retryRes = await this.request(url, { ...options, _retry: true });
                resolve(retryRes);
              } else {
                reject(new Error('获取微信登录凭证失败'));
              }
            } catch (loginError) {
              console.error('自动登录失败:', loginError);
              reject(new Error('登录已过期，请重新登录'));
            }
          } else {
            reject(new Error(res.data?.message || '请求失败'));
          }
        },
        fail: (err) => {
          reject(new Error('网络请求失败'));
        }
      });
    });
  }

  /**
   * 微信登录
   */
  async wechatLogin(code, userInfo) {
    try {
      const data = await this.request('/auth/login', {
        method: 'POST',
        data: {
          code,
          userInfo
        }
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户信息
   */
  async getUserProfile() {
    try {
      const data = await this.request('/auth/profile');
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 更新用户信息
   */
  async updateUserProfile(userData) {
    try {
      const data = await this.request('/auth/profile', {
        method: 'PUT',
        data: userData
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取治疗模板
   */
  async getTreatmentTemplates(params = {}) {
    try {
      const data = await this.request('/treatments/templates', {
        method: 'GET',
        data: params
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户治疗模板（不分页）
   */
  async getUserTreatmentTemplates() {
    try {
      const data = await this.request('/treatments/templates/user');
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 根据模板类型获取治疗模板
   */
  async getTemplatesByType(templateType) {
    try {
      const data = await this.request(`/treatments/templates/by-type/${templateType}`);
      return data;
    } catch (error) {
      throw error;
    }
  }
  
  async getUserTemplates(){
    try {
      const data = await this.request('/treatments/templates/user');
      return data;
    } catch (error) {
      throw error;
    } 
  }

  /**
   * 创建治疗模板
   */
  async createTreatmentTemplate(templateData) {
    try {
      const data = await this.request('/treatments/templates', {
        method: 'POST',
        data: templateData
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取治疗记录
   */
  async getTreatmentRecords(params = {}) {
    try {
      const data = await this.request('/treatments/records', {
        method: 'GET',
        data: params
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 创建治疗记录
   */
  async createTreatmentRecord(recordData) {
    try {
      const data = await this.request('/treatments/records', {
        method: 'POST',
        data: recordData
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取治疗统计
   */
  async getTreatmentStatistics() {
    try {
      const data = await this.request('/treatments/statistics');
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 删除治疗模板
   */
  async deleteTreatmentTemplate(templateId) {
    try {
      const data = await this.request(`/treatments/templates/${templateId}`, {
        method: 'DELETE'
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取音乐文件列表
   */
  async getMusicFiles(params = {}) {
    try {
      const data = await this.request('/music/files', {
        method: 'GET',
        data: params
      });
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取视频教程列表
   */
  async getVideoList() {
    try {
      const data = await this.request('/videos');
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取FAQ列表
   */
  async getFAQList() {
    try {
      const data = await this.request('/faq');
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取联系信息
   */
  async getContactInfo() {
    try {
      const data = await this.request('/contact');
      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取公司信息
   */
  async getCompanyInfo() {
    try {
      const data = await this.request('/about');
      return data;
    } catch (error) {
      throw error;
    }
  }
}

// 创建单例实例
const apiClient = new ApiClient();

module.exports = apiClient;